/*
 * DatagramBuilder Library: serialize/deserialize data to/from datagram
 * Copyright (C) 2008 Rakov Ilya <RakovIlya@gmail.com>
 *
 * This library can be distributed under the terms of the GNU LGPLv2.
 * See the file COPYING.LIB.
 */


#ifndef DATAGRAM_CRTPSCOPEDTRANSACTION_H_
#define DATAGRAM_CRTPSCOPEDTRANSACTION_H_


/**
 * @file CRTPScopedTransaction.h
 *
 * @brief CRTPScopedTransaction header file
 *
 * @date Dec 15, 2008
 * @author Rakov Ilya
 */


#include <stdexcept>

/**
 * @brief This template class provides a transaction mode.
 *
 * The CRTPScopedTransaction is based on Curiously Recurring Template Pattern.
 * @see http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Curiously_Recurring_Template_Pattern
 */
template< class Derived >
class CRTPScopedTransaction
{

public:

 ~CRTPScopedTransaction()
  {
    if ( std::uncaught_exception() )
      GetDerived()->Rollback();
    else
      GetDerived()->Commit();
  }


 /**
  * @brief Rollback transaction.
  *
  * This method will be invoked on CRTPScopedTransaction destruction
  * if uncaught exception is present.
  * Override this method to implement transaction rollback.
  */
  inline void Rollback()
  {
  }


  /**
   * @brief Commit transaction.
   *
   * This method will be invoked on CRTPScopedTransaction destruction
   * if uncaught exception is absent.
   * Override this method to implement transaction commit.
   */
  inline void Commit()
  {
  }


private:

  Derived* GetDerived()
  {
    return static_cast< Derived* >( this );
  }

};


#endif /* DATAGRAM_CRTPSCOPEDTRANSACTION_H_ */
